<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地图名称" prop="mapName">
        <el-input
          v-model="queryParams.mapName"
          placeholder="请输入地图名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="园区编号" prop="parkId">
        <el-select clearable
                   v-model="queryParams.parkNum"
                   placeholder="请选择园区"
        >
          <el-option
            v-for="item in parkList"
            :key="item.id"
            :label="item.parkNum"
            :value="item.parkNum"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:sysMap:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:sysMap:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:sysMap:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sysMapList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="地图名称" align="center" prop="mapName" />
      <el-table-column label="地图url" align="center" prop="mapUrl" >
        <template slot-scope="scope">
          <img :src="scope.row.mapUrl" alt="" style="width: 100px">
        </template>
      </el-table-column>
      <el-table-column label="园区号" align="center" prop="parkNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sysMap:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="goToSignFn(scope.row)"
            v-hasPermi="['system:sysMap:edit']"
          >标点</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:sysMap:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改园区地图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="地图名称" prop="mapName">
          <el-input v-model="form.mapName" placeholder="请输入地图名称" />
        </el-form-item>
        <el-form-item label="地图url" prop="mapUrl">
          <el-upload
            list-type="picture-card"
            accept=".png, .jpg"
            :limit="1"
            :class="{hideAdd:coverAddhide}"
            :file-list="coverImag"
            action
            :http-request="HandleUploadSelf"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :on-preview="handlepreview"
            :on-change="onChange"
            :on-error="onError"
          >
            <i class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="园区编号" prop="parkId">
          <el-select clearable
                     v-model="form.parkNum"
                     placeholder="请选择园区"
          >
            <el-option
              v-for="item in parkList"
              :key="item.id"
              :label="item.parkNum"
              :value="item.parkNum"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSysMap, getSysMap, delSysMap, addSysMap, updateSysMap } from "@/api/system/sysMap";
import {listBuiPark} from "@/api/parkAssets/enterCommunity";
import axios from "axios";
import {getToken} from "@/utils/auth";

export default {
  name: "SysMap",
  components: {
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/file/upload",
      parkList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      coverAddhide:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      coverImag:[],
      // 园区地图表格数据
      sysMapList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mapName: null,
        mapUrl: null,
        parkNum: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    listBuiPark().then((response) =>{
      this.parkList = response.rows;
    })
  },
  methods: {
    /** 查询园区地图列表 */
    getList() {
      this.loading = true;
      listSysMap(this.queryParams).then(response => {
        this.sysMapList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mapName: null,
        mapUrl: null,
        parkNum: null,
        updateTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加园区地图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSysMap(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改园区地图";
        if (this.isEmpty(this.form.mapUrl)) {
          this.coverImag = [];
        } else {
          this.coverImag = [{url: this.form.mapUrl}];
          this.coverAddhide = true;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSysMap(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSysMap(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleUploadSuccess(){
      // this.loading.close();
    },
    handleBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 3;
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      console.log("isLt2M",isLt2M)
      if (!isLt2M) {
        this.$message.error('封面图片大小不能超过 3MB!');
        this.loading.close();
      }
      return isLt2M;
    },
    // 封面自定义上传图片
    HandleUploadSelf(file, fileList) {
      axios({
        method: "post",
        url: this.uploadFileUrl,
        data: this.formData({file: file.file}),
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + getToken(),
        },
        //上传进度
        onUploadProgress: (progressEvent) => {
          this.progressFlag = true;
          this.loadProgress =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          if (this.loadProgress >= 99) {
            this.loadProgress = 99;
          }
        },
      })
        .then((resf) => {
          let res = resf.data;
          if (res.code === 200) {
            this.progressFlag = false;
            this.loadProgress = 100;
            this.form.mapUrl = "http://" + res.data.url;
            this.loading.close();
            this.$message.success("上传成功");
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          console.log(error);
        });

      // fileupload(this.formData({ file: file.file })).then((res) => {
      //   if (res.code === 200) {
      //     this.msgSuccess(res.msg);
      //     this.form.newsPic = "http://" + res.data.url;
      //   }
      // });
    },
    // 封面图片移除
    handleRemove(file, fileList) {
      console.log(fileList, "封面图片移除");
      this.coverImag = fileList;
      this.form.mapUrl = ""
      this.coverAddhide = this.coverImag.length >= 1;
    },
    goToSignFn(row){
      this.$router.push({
        name: "MapSign",
        query: { id: row.id ,mapUrl:row.mapUrl },
      });
    },
    onError(){
      this.loading.close();
    },
    // 封面图片发生变化
    onChange(file, fileList) {
      this.coverImag = fileList;
      this.coverAddhide = this.coverImag.length >= 1;
    },
    // 封面缩略图
    handlepreview(file) {
      this.dialogVisible = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除园区地图编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delSysMap(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sysMap/export', {
        ...this.queryParams
      }, `system_sysMap.xlsx`)
    }
  }
};

</script>

<style lang="scss" scoped>
::v-deep .hideAdd .el-upload--picture-card {
  display: none !important; /* 上传按钮隐藏 */
}
</style>
